import React, { useEffect, useState, useRef, act } from 'react';
import ROSLIB from 'roslib';
import { Button, Space, message, Input, Card, Descriptions, Switch, Progress, Slider, Form, Row, Col, Tag } from 'antd';
import { PageContainer, ProFormInstance, ProFormSelect } from '@ant-design/pro-components';
import './index.scss'
import Draggable from 'react-draggable';
import {
    ProFormDatePicker,
    ProFormText,
    QueryFilter,
} from '@ant-design/pro-components';
import { CaretDownOutlined, CaretLeftOutlined, CaretRightOutlined, CaretUpOutlined, LeftCircleFilled, PlayCircleFilled, RightCircleFilled } from '@ant-design/icons';
import { useAccess } from '@umijs/max';
import { getAssetList, getDeviceNumsByName, getDeviceIpByNum, getOnlineDeviceNames } from '@/services/manage/asset';
import { speakOn, speakOff, connect, disconnect, send } from '@/services/home/remote';
import { set } from 'lodash';
import e from 'express';


const MyDraggable = () => (
    <Draggable>
        <button style={{ padding: '10px 20px' }}>可拖动按钮</button>
    </Draggable>
);

const Remote: React.FC = () => {
    const positionPresets = {
        forward: { x: 1, y: 0, z: 0, yaw: 0 },
        backward: { x: -1, y: 0, z: 0, yaw: 0 },
        left: { x: 0, y: 0, z: 0, yaw: 1 },
        right: { x: 0, y: 0, z: 0, yaw: -1 },
        leftshift: { x: 0, y: 1, z: 0, yaw: 0 },
        rightshift: { x: 0, y: -1, z: 0, yaw: 0 },
        sport: { x: 0, y: 0, z: 0, yaw: 0 } // 运动模式
    };
    const [server, setServer] = useState('ws://192.168.0.186:8001/ws');
    const [ros, setRos] = useState<ROSLIB.Ros | null>(null);
    const [status, setStatus] = useState('未连接');
    const [log, setLog] = useState<string[]>([]);
    const [socket, setSocket] = useState<WebSocket | null>(null);
    const [commandJson, setCommandJson] = useState(JSON.stringify(positionPresets.forward));
    const [customTopic, setCustomTopic] = useState('api/sport/request');
    const [msgApi, contextHolder] = message.useMessage();
    const videoRef = useRef<HTMLVideoElement>(null);
    const [videoUrl, setVideoUrl] = useState<string>('');
    const [deviceNums, setDeviceNums] = useState<string[]>([]);
    const [onlineDevices, setOnlineDevices] = useState<string[]>([]);
    const [device, setDevice] = useState<API.Manage.Asset>();
    const formRef = useRef<ProFormInstance>();
    const [linearSpeed, setLinearSpeed] = useState(0.3);
    const [angularSpeed, setAngularSpeed] = useState(0.3);
    const linearSpeedRef = useRef(linearSpeed); // 使用 useRef 保持速度状态
    const angularSpeedRef = useRef(angularSpeed); // 使用 useRef 保持角速度状态
    const access = useAccess();
    const [position, setPosition] = useState({ x: 0, y: 0, z: 0, yaw: 0 });
    const logRef = useRef<HTMLDivElement>(null);
    const sendTimestampRef = useRef<number>(0);
    const socketRef = useRef<WebSocket | null>(null);
    const [ip, setIp] = useState<string>('192.168.0.186');
    const sportId = useRef<number>(0); // 使用 useRef 保持 sportId 状态
    const [showDeviceInfo, setShowDeviceInfo] = useState(false);
    const [speakStatus, setSpeakStatus] = useState('未对讲');
    const [activeButton, setActiveButton] = useState<string | null>(null); // 用于跟踪当前激活的按钮
    const [down, setDown] = useState(false); // 用于跟踪设备是否趴下



    const logMessage = (msg: string) => {
        setLog(prev => [...prev.slice(-49), `[${new Date().toLocaleTimeString()}] ${msg}`]);
    };

    // const connect = () => {
    //     if (socket) socket.close();
    //     logMessage('连接中...');
    //     setStatus('connecting');

    //     const ws = new WebSocket(server);

    //     ws.onopen = () => {
    //         logMessage('✅ 已连接 ROS WebSocket');
    //         setStatus('连接成功');
    //         socketRef.current = ws; // 👈 绑定到 ref
    //     };
    //     ws.onerror = err => {
    //         logMessage('❌ WebSocket 错误');
    //         setStatus('连接失败');
    //     };
    //     ws.onclose = () => {
    //         logMessage('⚠️ 已断开连接');
    //         setStatus('连接失败');
    //     };

    //     // ✅ 添加这段监听消息的处理逻辑
    //     ws.onmessage = (event) => {
    //         try {
    //             const msg = JSON.parse(event.data);
    //             console.log('收到消息:', msg);
    //             // ✅ 仅当是你自己发送请求后的响应时，才计算延时
    //             if (msg.code === 200) {
    //                 const sendTime = sendTimestampRef.current;
    //                 const delay = Date.now() - sendTime;
    //                 //   logMessage(`📩 当前时间戳: ${Date.now()}`);
    //                 logMessage(`延时: ${delay}毫秒`);
    //             }

    //         } catch (err) {
    //             logMessage(`⚠️ 无法解析ROS返回: ${event.data}`);
    //         }
    //     };
    //     setSocket(ws);
    //     // console.log('WebSocket连接已建立:', ws);    
    // };

    // const onConnect = () => {
    //     connect()
    // }

    const onDisconnect = () => {
        if (status === '连接成功') {
            disconnect(ip).then((res) => {
                if (res.code === 200) {
                    setStatus('断开连接');
                    logMessage('⚠️ 已断开连接');
                } else {
                    message.error('断开连接失败');
                }
            })
        } else {
            message.error('未连接设备');
        }
        // socket?.close();
        // setSocket(null);
        // socketRef.current = null;
    };

    const applyPreset = async (presetKey: keyof typeof positionPresets, sportId: number) => {
        const preset = positionPresets[presetKey];
        const data = {
            x: preset.x * linearSpeedRef.current,
            y: preset.y * linearSpeedRef.current,
            z: preset.z * linearSpeedRef.current,
            yaw: preset.yaw * angularSpeedRef.current
        }
        const msg = { ip: ip, topic: '/' + customTopic, data: data, sportId: sportId };
        // const sock = socketRef.current;
        // if (sock && sock.readyState === WebSocket.OPEN) {
        //     const sendTime = Date.now();
        //     sendTimestampRef.current = sendTime;
        //     sock.send(JSON.stringify(msg));
        //     // logMessage(`📩 发送时间戳: ${sendTime}`);
        //     logMessage(`🚀 已发送指令: ${JSON.stringify(msg)}`);
        // } else {
        //     message.error('未连接 WebSocket');
        // }
        if (status === '连接成功') {
            await send(msg).then((res) => {
                if (res.code === 200) {
                    logMessage(`🚀 已发送指令: ${JSON.stringify(msg)}`);
                }
            }).catch((error) => {
                message.error('发送指令失败: ' + error.message);
            })
        }
        // 仍然可以同步更新 UI 状态
        setPosition(data);
        setCommandJson(JSON.stringify(data, null, 2));
    };

    //获取在线设备名称
    const getonlineDevices = async () => {
        try {
            if (access.hasPerms('inspection:asset:allOnlineDeviceName')) {
                const onlineDevices = await getOnlineDeviceNames();
                const deviceNameList = Array.isArray(onlineDevices?.rows) ? onlineDevices.rows : [];
                setOnlineDevices(deviceNameList);

            }
        }
        catch (error) {
            message.error('获取设备名称失败:');
            setOnlineDevices([]);
        }
    }

    useEffect(() => {
        getonlineDevices();  // 初始调用
        const interval = setInterval(() => {
            getonlineDevices();  // 每隔一段时间刷新
        }, 5000); // 每5秒刷新一次
        if (down === false && device?.batteryLevel !== undefined && device.batteryLevel <= 8) {
            message.warning('设备电量低于8%, 5秒后设备将趴下, 请及时充电！');
            const setT = setTimeout(() => {
                applyPreset('sport', 1005); // 趴下
            }, 5000); // 5秒后执行
            setDown(true); // 设置 down 状态为 true，避免重复执行
            clearTimeout(setT); // 清除定时器
        }
        return () => {
            clearInterval(interval);
        } // 清理定时器
    }, []);

    useEffect(() => {
        const jsonData = { ...position };
        setCommandJson(JSON.stringify(jsonData, null, 2));
    }, [position]);

    useEffect(() => {
        logRef.current?.scrollTo({ top: logRef.current.scrollHeight, behavior: 'smooth' });
    }, [log]);

    const activeKeyDown = (key: keyof typeof positionPresets, sportId: number) => {
        applyPreset(key, sportId);
        if(key== 'sport') {
            switch (sportId) {
                case 1009:
                    setActiveButton('sport1');
                    break;
                case 1010:
                    setActiveButton('sport2');
                    break;
                case 1016:
                    setActiveButton('sport3');
                    break;
                case 1017:
                    setActiveButton('sport4');
                    break;
                case 1021:
                    setActiveButton('sport5');
                    break;
                case 1022:
                    setActiveButton('sport6');
                    break;
                case 1005:
                    setActiveButton('sport7');
                    break;
                case 1030:
                    setActiveButton('sport8');
                    break;
                case 1031:
                    setActiveButton('sport9');
                    break;
                case 1032:
                    setActiveButton('sport10');
                    break;
            }
        }
        else setActiveButton(key)        
        setTimeout(() => setActiveButton(null), 100); // 300毫秒后取消激活状态
    }

    useEffect(() => {
        linearSpeedRef.current = linearSpeed;
        angularSpeedRef.current = angularSpeed;
        const handleKeyDown = (event: KeyboardEvent) => {
            if (
                ['INPUT', 'TEXTAREA', 'SELECT'].includes((event.target as HTMLElement).tagName)
            ) {
                return;
            }

            switch (event.key.toLowerCase()) {
                case 'w':
                    activeKeyDown('forward', 1008);
                    break;
                case 's':
                    activeKeyDown('backward', 1008);
                    break;
                case 'a':
                    activeKeyDown('left', 1008);
                    break;
                case 'd':
                    activeKeyDown('right', 1008);
                    break;
                case 'q':
                    activeKeyDown('leftshift', 1008);
                    break;
                case 'e':
                    activeKeyDown('rightshift', 1008);
                    break;
                case 'r':
                    activeKeyDown('sport', 1009);
                    break;
                case 't':
                    activeKeyDown('sport', 1010);
                    break;
                case 'y':
                    activeKeyDown('sport', 1016);
                    break;
                case 'u':
                    activeKeyDown('sport', 1017);
                    break;
                case 'i':
                    activeKeyDown('sport', 1021);
                    break;
                case 'f':
                    activeKeyDown('sport', 1022);
                    break;
                case 'g':
                    activeKeyDown('sport', 1005); // 趴下
                    break;
                case 'h':
                    activeKeyDown('sport', 1030);
                    break;
                case 'j':
                    activeKeyDown('sport', 1031);
                    break;
                case 'k':
                    activeKeyDown('sport', 1032);
                    break;
                default:
                    break;
            }

        };
        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, [linearSpeed, angularSpeed]);

    useEffect(() => {
        const handleBeforeUnload = () => {
            onDisconnect();
        };

        window.addEventListener('beforeunload', handleBeforeUnload);

        return () => {
            window.removeEventListener('beforeunload', handleBeforeUnload);
        };
    }, []);

    useEffect(() => {
        if (!device || status !== '连接成功') return;
        const interval = setInterval(async () => {
            await getAssetList({ deviceNum: device.deviceNum }).then((res) => {
                if (res.code === 200) {
                    setDevice(res?.rows[0]);
                }
            })
        }, 30000)
        return () => clearInterval(interval);
    }, [device, status]);

    // 发布运动请求
    const publishRequest = (apiId: number, params: Record<string, any> = {}, binary: number[] = []) => {
        if (!ros) return;

        const topic = new ROSLIB.Topic({
            ros: ros,
            name: '/api/sport/request',
            messageType: 'unitree_api/Request' // 使用已注册的类型
        });

        const now = Date.now();
        const message = new ROSLIB.Message({
            header: {
                stamp: { secs: Math.floor(now / 1000), nsecs: (now % 1000) * 1e6 },
                frame_id: 'web',
                identity: {
                    api_id: apiId,
                    reserved: 0,
                    version: 1
                }
            },
            parameter: JSON.stringify(params),
            binary: binary
        });

        topic.publish(message);
        console.log('已发送:', message);
    };


    const onFinish = async (queryParams: { deviceName: String, deviceNum: String }) => {
        console.log('查询参数：', queryParams);
        await getDeviceIpByNum(queryParams.deviceNum as string).then((res) => {
            if (res.code === 200) {
                const deviceIp = res?.rows[0];
                setIp(deviceIp);
                setServer(`ws://${deviceIp}:8001/ws`);
            } else {
                message.error('获取设备IP地址失败');
            }
        })
        await getAssetList(queryParams as API.Manage.AssetListParams).then((res) => {
            if (res.code === 200) {
                const device = res?.rows[0] || [];
                // 连接到 ROS WebSocket
                connect(device.ipAddress).then((resp) => {
                    if (resp.code === 200) {
                        setStatus('连接成功');
                        logMessage('✅ 已连接 ROS WebSocket');
                        setDevice(device);
                    } else {
                        setStatus('连接失败');
                        message.error('连接 ROS WebSocket 失败');
                        logMessage('❌ 连接 ROS WebSocket 失败');
                    }
                })
            }
        }
        )
    }

    return (
        <PageContainer>
            {contextHolder}
            <QueryFilter defaultCollapsed split
                formRef={formRef}
                style={{ backgroundColor: '#141414', marginBottom: "10px", borderRadius: '5px' }}
                onFinish={(queryParams) => onFinish(queryParams as { deviceName: string, deviceNum: string })}
                onReset={() => {
                    setDevice(undefined);
                    onDisconnect()
                }}
                submitter={{
                    searchConfig: {
                        submitText: '连接',     // 把“查询”改成“连接”
                        resetText: '重置'
                    }
                }}
            >
                <ProFormSelect
                    name="deviceName"
                    label='设备名称'
                    options={onlineDevices}
                    placeholder="请选择在线设备名称"
                    rules={[{ required: true, message: '请选择在线设备名称!' }]}
                    onChange={async (value: string | undefined) => {
                        if (value && access.hasPerms('inspection:asset:deviceNums')) {
                            const deviceNum = await getDeviceNumsByName(value);
                            setDeviceNums(deviceNum?.rows);
                            console.log('设备编号:', deviceNum?.rows);

                        } else {
                            // 清空设备编号选项和字段值
                            setDeviceNums([]);
                            formRef.current?.setFieldsValue({ deviceNum: undefined });
                        }
                    }}
                />
                <ProFormSelect
                    name="deviceNum"
                    label='设备编号'
                    placeholder="请选择设备编号"
                    options={deviceNums}
                    rules={[{ required: true, message: "请选择设备编号!" }]}
                />
            </QueryFilter>

            <div className='container'>
                <div className='video-control'>
                    <div className='video-container'>
                        <div>
                            <div>连接状态：<span style={{ color: status === '连接成功' ? 'green' : status === 'connecting' ? 'orange' : 'red' }}>{status}</span>&nbsp;&nbsp;&nbsp;&nbsp;对讲状态：<span style={{ color: speakStatus === '未对讲' ? 'gray' : 'green' }}>{speakStatus}</span></div>
                            <Button type="primary" className='speak' onClick={async () => {
                                if (status === '连接成功') {
                                    if (speakStatus === '未对讲') {
                                        await speakOn({ ip: ip, port: 8899 }).then((res) => {
                                            if (res.code === 200) {
                                                setSpeakStatus('已对讲');
                                            } else {
                                                message.error('开启对讲失败');
                                            }
                                        })
                                    } else {
                                        message.success('已开启对讲');
                                    }
                                } else {
                                    message.warning('请先连接设备');
                                }
                            }
                            }>开启对讲</Button>
                            <Button type="primary" className='speak' onClick={async () => {
                                if (status === '连接成功' && speakStatus === '已对讲') {
                                    await speakOff({ ip: ip, port: 8899 }).then((res) => {
                                        if (res.code === 200) {
                                            setSpeakStatus('未对讲')
                                        } else {
                                            message.error('关闭对讲失败');
                                        }
                                    })
                                } else {
                                    message.warning('请开启对讲或未连接设备');
                                }
                            }}>结束对讲</Button>
                            <Button danger type="primary" className='speak' onClick={onDisconnect}>断开</Button>
                        </div>
                        {/* <iframe id="cameraFrame" src={`http://${ip}:8889/camera`}></iframe>   */}
                        {status === '连接成功' ? (
                            <iframe
                                id="cameraFrame"
                                src={`http://${ip}:8889/camera`}
                                style={{ width: '100%', height: '100%', border: 'none' }}
                            />
                        ) : (
                            <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#aaa' }}>
                                请先连接设备以查看监控视频
                            </div>
                        )}
                    </div>
                    <div className='control'>
                        <div className='control-header'>
                            <div className="circle-control">
                                <button
                                    className={`button up ${activeButton == 'forward' ? 'active' : ''}`}
                                    onClick={() => { activeKeyDown('forward', 1008) }}
                                >
                                    <CaretUpOutlined />
                                </button>

                                <button
                                    className={`button left ${activeButton == 'left' ? 'active' : ''}`}
                                    onClick={() => activeKeyDown('left', 1008)}
                                >
                                    <CaretLeftOutlined />
                                </button>
                                <button
                                    className="text-button"
                                    onClick={() => publishRequest(1008, { x: 0.2 })}
                                >
                                    位置
                                </button>
                                {/* <Draggable>
                                    <button className="text-button"
                                    onClick={() => publishRequest(1008, { x: 0.2 })}
                                    >位置</button>
                                </Draggable> */}

                                <button
                                    className={`button right ${activeButton == 'right' ? 'active' : ''}`}
                                    onClick={() => activeKeyDown('right', 1008)}
                                >
                                    <CaretRightOutlined />
                                </button>
                                <button
                                    className={`button down ${activeButton == 'backward' ? 'active' : ''}`}
                                    onClick={() => activeKeyDown('backward', 1008)}
                                >
                                    <CaretDownOutlined />
                                </button>
                                <button
                                    className={`button leftshift ${activeButton == 'leftshift' ? 'active' : ''}`}
                                    onClick={() => activeKeyDown('leftshift', 1008)}
                                >
                                    <LeftCircleFilled />
                                </button>
                                <button
                                    className={`button rightshift ${activeButton == 'rightshift' ? 'active' : ''}`}
                                    onClick={() => activeKeyDown('rightshift', 1008)}
                                >
                                    <RightCircleFilled />
                                </button>
                                <div className='button-container' style={{ marginTop: '400px' }}>
                                    <Button type="primary" onClick={() => activeKeyDown('sport', 1009)}
                                        className={`buttons ${activeButton == 'sport1' ? 'active1' : ''}`}>坐下</Button>
                                    <Button type="primary" onClick={() => activeKeyDown('sport', 1010)} 
                                        className={`buttons ${activeButton == 'sport2' ? 'active1' : ''}`}>恢复站立</Button>
                                    <Button type="primary" onClick={() => activeKeyDown('sport', 1016)} 
                                        className={`buttons ${activeButton == 'sport3' ? 'active1' : ''}`}>打招呼</Button>
                                    <Button type="primary" onClick={() => activeKeyDown('sport', 1017)} 
                                        className={`buttons ${activeButton == 'sport4' ? 'active1' : ''}`}>伸展</Button>
                                    <Button type="primary" onClick={() => activeKeyDown('sport', 1021)} 
                                        className={`buttons ${activeButton == 'sport5' ? 'active1' : ''}`}>打滚</Button>
                                </div>
                                <div className='button-container' style={{ marginTop: '10px' }}>
                                    <Button type="primary" onClick={() => activeKeyDown('sport', 1022)} 
                                        className={`buttons ${activeButton == 'sport6' ? 'active1' : ''}`}>舞蹈</Button>
                                    <Button type="primary" onClick={() => activeKeyDown('sport', 1005)} 
                                        className={`buttons ${activeButton == 'sport7' ? 'active1' : ''}`}>趴下</Button>
                                    <Button type="primary" onClick={() => activeKeyDown('sport', 1030)} 
                                        className={`buttons ${activeButton == 'sport8' ? 'active1' : ''}`}>前空翻</Button>
                                    <Button type="primary" onClick={() => activeKeyDown('sport', 1031)}
                                        className={`buttons ${activeButton == 'sport9' ? 'active1' : ''}`}>前跳</Button>
                                    <Button type="primary" onClick={() => activeKeyDown('sport', 1032)} 
                                        className={`buttons ${activeButton == 'sport10' ? 'active1' : ''}`}>前扑</Button>
                                </div>
                            </div>
                            <div className='speed'>
                                {/* <Button
                                    className="speed-button"
                                    onClick={() => publishRequest(1008, { speed: 0.5 })}
                                >
                                    低速
                                </Button>
                                <Button
                                    className="speed-button"
                                    onClick={() => publishRequest(1008, { speed: 0.5 })}
                                >
                                    中速
                                </Button>
                                <Button
                                    className="speed-button"
                                    onClick={() => publishRequest(1008, { speed: 0.5 })}
                                >
                                    高速
                                </Button> */}
                                <div className="speed_div">线速度</div>
                                <Slider
                                    vertical
                                    min={0.3}
                                    max={3}
                                    step={0.01}
                                    value={linearSpeed}
                                    onChange={(value) => { setLinearSpeed(value); }}
                                    style={{ height: 150 }}
                                    marks={{ 0.3: '0.3', 3: '3' }}
                                />
                                <div className="speed_div">角速度</div>
                                <Slider
                                    vertical
                                    min={0.3}
                                    max={2}
                                    step={0.01}
                                    value={angularSpeed}
                                    onChange={(value) => setAngularSpeed(value)}
                                    style={{ height: 150 }}
                                    marks={{ 0.3: '0.3', 2: '2' }}
                                />

                                <Button
                                    className='speed-button'
                                    style={{ marginTop: 12 }}
                                    onClick={() => {
                                        setLinearSpeed(0.2);
                                        setAngularSpeed(0.2);
                                    }}
                                >
                                    重置
                                </Button>
                            </div>
                        </div>
                    </div>
                    <div className="flatten" >
                        <Button
                            type="link"
                            onClick={() => setShowDeviceInfo(!showDeviceInfo)}
                            icon={<CaretDownOutlined rotate={showDeviceInfo ? 180 : 0} />}
                        >
                            {showDeviceInfo ? '收起设备信息' : '展开设备信息'}
                        </Button>
                    </div>
                </div>
                <div className='device-info'>
                    {showDeviceInfo && (<Row >
                        <Col span={12}>
                            <Card
                                title={<span style={{ fontSize: '24px', fontWeight: 600, textAlign: 'center' }}>设备信息</span>}
                                variant="borderless"
                            // className="card-container"
                            // style={{ visibility: device ? 'visible' : 'hidden' }}
                            >
                                <Descriptions
                                    bordered
                                    column={1}
                                    size="small"
                                    styles={{
                                        label: { width: 120, fontWeight: 500, fontSize: '20px' },
                                        content: { fontSize: '20px' }
                                    }}
                                >
                                    <Descriptions.Item label="设备名称">{device?.deviceName}</Descriptions.Item>
                                    <Descriptions.Item label="设备编号">{device?.deviceNum}</Descriptions.Item>
                                    <Descriptions.Item label="设备类型">{device?.deviceType}</Descriptions.Item>
                                    <Descriptions.Item label="IP地址">
                                        <Tag style={{ fontSize: '20px', color: "#177DDC" }}>{device?.ipAddress}</Tag>
                                    </Descriptions.Item>

                                    {/* 电池电量 Progress 只读 */}
                                    <Descriptions.Item label="电池电量">
                                        <Progress
                                            percent={device?.batteryLevel}
                                            size="small"
                                            status={(device?.batteryLevel ?? 0) < 20 ? 'exception' : 'normal'}
                                            strokeColor={(device?.batteryLevel ?? 0) < 20 ? '#ff4d4f' : '#1890ff'}
                                            format={percent => `${percent ?? 0}%`}
                                        />
                                    </Descriptions.Item>

                                    {/* 是否在线 Switch 只读 */}
                                    <Descriptions.Item label="是否在线">
                                        <Switch checked={!!device?.isOnline} disabled />
                                    </Descriptions.Item>

                                    {/* 网络状态 Switch 只读 */}
                                    <Descriptions.Item label="网络状态">
                                        <Switch checked={device?.networkStatus === 1} disabled />
                                    </Descriptions.Item>

                                    <Descriptions.Item label="最近在线">{device?.lastOnline}</Descriptions.Item>
                                    <Descriptions.Item label="创建时间">{device?.createTime || '—'}</Descriptions.Item>
                                    <Descriptions.Item label="更新时间">{device?.updateTime || '—'}</Descriptions.Item>
                                </Descriptions>
                            </Card>
                        </Col>
                        <Col span={12}  >
                            <Card title="连接管理">
                                <Form layout="vertical">
                                    <Form.Item label="服务器地址">
                                        {/* <Input value={server} onChange={e => setServer(e.target.value)}/> */}
                                        <Input value={server} disabled />
                                    </Form.Item>
                                    {/* <Form.Item>
                                    <Space>
                                        <Button type="primary" onClick={async ()=>{
                                            await connect(ip).then(() => {
                                                setStatus('连接成功');
                                                logMessage('✅ 已连接 ROS WebSocket')})                                        
                                            }}>连接</Button>
                                        <Button danger onClick={onDisconnect}>断开</Button>
                                    </Space>
                                </Form.Item> */}
                                </Form>
                            </Card>
                            <Card title="系统日志">
                                <div ref={logRef} style={{ maxHeight: 290, height: 290, overflowY: 'auto', fontFamily: 'monospace' }}>
                                    {log.map((line, i) => <div key={i}>{line}</div>)}
                                </div>
                            </Card>
                        </Col>
                    </Row>)}
                </div>

            </div>


        </PageContainer>
    );
};

export default Remote;